package com.lhy.tool.database.table;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.autoconfigure.MybatisPlusProperties;
import com.lhy.tool.autoconfigation.GeneratorProperties;
import com.lhy.tool.database.*;
import com.lhy.tool.database.converter.DbColumnTypeConverterHelper;
import com.lhy.tool.database.mapper.DbMetaDataMapper;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.stream.Collectors;

public abstract class AbstractDbMetaDataProcessor<T extends DbMetaDataMapper> implements DbMetaDataProcessor {

    @Autowired
    GeneratorProperties generatorProperties;

    @Autowired
    MybatisPlusProperties mybatisPlusProperties;

    @Autowired
    DbColumnTypeConverterHelper dbColumnTypeConverterHelper;

    @Autowired
    private T metaDataMapper;

    @Override
    public List<Table> listTable(List<String> tableNames) {
        List<TableMetaData> tableMetaDataList = metaDataMapper.listTable(generatorProperties.getDataBaseConfig().getSchema(), tableNames);
        return tableMetaDataList.stream().map(tableMetaData -> {
            Table table = new Table();
            setTableProperty(tableMetaData, table);
            setTableColumns(table);
            return table;
        }).collect(Collectors.toList());
    }

    private void setTableProperty(TableMetaData tableMetaData, Table table) {
        table.setName(tableMetaData.getName()).setComment(tableMetaData.getComments());
    }

    private void setTableColumns(Table table) {
        List<TableColumnMetaData> tableColumnMetaData = metaDataMapper.listTableColumns(generatorProperties.getDataBaseConfig().getSchema(), table.getName());
        List<TableColumn> tableColumns = tableColumnsMapToBean(tableColumnMetaData);
        table.setColumns(tableColumns);
    }

    private List<TableColumn> tableColumnsMapToBean(List<TableColumnMetaData> tableColumnMetaData) {
        return tableColumnMetaData.stream().map(metaData -> {
            TableColumn tableColumn = new TableColumn()
                    .setName(metaData.getName())
                    .setComment(metaData.getComments());
            if (isPrimaryKey(metaData)) {
                tableColumn.setKeyFlag(true);
                IdType idType = mybatisPlusProperties.getGlobalConfig().getDbConfig().getIdType();
                tableColumn.setIdType(idType.name());
            }
            DbColumnType dbColumnType = dbColumnTypeConverterHelper.converter(metaData.getType().toLowerCase());
            tableColumn.setColumnType(dbColumnType);
            return tableColumn;
        }).collect(Collectors.toList());
    }


    protected boolean isPrimaryKey(TableColumnMetaData metaData) {
        return "PRI".equals(metaData.getKey());
    }


}
